<script setup name="Identify">
import { getCurrentInstance, ref, shallowRef } from "vue";
import { addCompanyIdentify, delCompanyIdentify, editCompanyIdentify, getCompanyIdentifyPage, getDetailsByKey } from "@/api/company/identify";
import Pagination from "@/components/Pagination/index.vue";
import { getToken } from "@/utils/auth";

const { proxy } = getCurrentInstance();

const queryForm = shallowRef(null);
const queryParams = ref({
	// 企业名称
	searchText: null,
	pageNum: 1,
	pageSize: 10,
});
const total = ref(0);
const rowId = ref(null);
const rowData = ref({
	id: null,
	name: null,
	addr: null,
	grade: null,
	num: null,
	remark: null,
	fileUrl: null,
	createTime: null,
	updateTime: null,
});
const loading = ref(false);

const tableData = ref([]);

const editVisible = ref(false);

// 查询
const search = async () => {
	await getTableData(queryParams.value);
};

// 获取列表
const getTableData = async (params) => {
	loading.value = true;
	const res = await getCompanyIdentifyPage({
		...params,
	});
	try {
		console.log(res);
		if (res.code === 200) {
			tableData.value = res.data.records;
			total.value = res.data.total;
		}
	} catch (e) {
		console.log(e);
	} finally {
		setTimeout(() => {
			loading.value = false;
		}, 1e3);
	}
};

// 新增
const addIdentify = () => {
	editVisible.value = true;
};
// 编辑
const handleUpdate = (row) => {
	editVisible.value = true;
	rowId.value = row.id;
};
// 删除
const handleDelete = (row) => {
	const id = row.id;
	proxy.$modal
		.confirm('是否确认删除企业证书编号为"' + id + '"的数据项?')
		.then(async function () {
			return delCompanyIdentify({ id });
		})
		.then(() => {
			getTableData();
			proxy.$modal.msgSuccess("删除成功");
		})
		.catch(() => {});
};

const formData = ref({
	name: null,
	addr: null,
	grade: null,
	num: null,
	fileId: null,
	fileUrl: null,
	remark: null,
});
// const elForm = shallowRef(null)
// const fileId = shallowRef(null)
const fileAction = import.meta.env.VITE_APP_BASE_API + "/enterpriseCertificate/upload";

const rules = {
	name: [
		{
			required: true,
			message: "请输入企业名称",
			trigger: "blur",
		},
	],
	addr: [
		{
			required: true,
			message: "请输入企业地址",
			trigger: "blur",
		},
	],
	grade: [
		{
			required: true,
			message: "请输入证书等级",
			trigger: "change",
		},
	],
	num: [
		{
			required: true,
			message: "请输入证书编号",
			trigger: "blur",
		},
	],
	fileId: [
		{
			required: true,
			message: "请上传证书",
			trigger: "blur",
		},
	],
	remark: [],
};
const clearFile = () => {
	formData.value.fileUrl = null;
	formData.value.fileId = null;
	proxy.$refs["fileId"].clearFiles();
};
const imageList = ref([]);
const photoBeforeUpload = (file) => {
	let isRightSize = file.size / 1024 / 1024 < 20;
	if (!isRightSize) {
		proxy.$modal.msgError("文件大小超过 20MB");
	}
	return isRightSize;
};

const handleRemove = (file, fileList) => {
	formData.value.fileUrl = null;
	formData.value.fileId = null;
};
const uploadSuccess = (response, file, fileList) => {
	if (response.code === 200) {
		formData.value.fileId = response.data.id;
		formData.value.fileUrl = response.data.accessUrl;
	} else {
		formData.value.fileId = null;
		formData.value.fileUrl = null;
	}
};

const onOpen = async () => {
	// editVisible.value = true;
	formData.value.fileUrl = null;
	if (rowId.value) {
		imageList.value = [];
		const res = await getDetailsByKey({ id: rowId.value });
		try {
			if (res.code === 200) {
				formData.value = res.data;
				res.data.zsFiles.forEach((element) => {
					imageList.value.push({
						name: element.originalName,
						url: element.accessUrl,
						...element,
					});
				});
				formData.value.fileId = res.data.zsFiles[0].id;
			} else {
			}
		} catch (e) {
			console.log(e);
		}
	}
};

const closeDialog = () => {
	editVisible.value = false;
	clearFile();
	proxy.resetForm("elForm");
};

const onClose = async () => {
	rowId.value = null;
	clearFile();
};

const submitForm = async () => {
	proxy.$refs["elForm"].validate(async (valid) => {
		if (valid) {
			const params = {
				...formData.value,
			};
			if (params.createTime) delete params.createTime;
			if (params.fileUrl) delete params.fileUrl;
			if (params.updateTime) delete params.updateTime;
			let res;
			if (rowId.value) {
				res = await editCompanyIdentify(params);
			} else {
				res = await addCompanyIdentify(params);
			}
			try {
				if (res.code === 200) {
					closeDialog();
					await getTableData();
				}
			} catch (e) {
				console.log(e);
			}
		}
	});
};

getTableData();
</script>

<template>
	<div class="app-container">
		<el-form ref="queryForm" :model="queryParams" inline label-width="68px" @submit.native.prevent>
			<el-form-item label="关键字" prop="searchText">
				<el-input :style="{ width: '200px' }" v-model="queryParams.searchText" clearable placeholder="请输入关键字"> </el-input>
			</el-form-item>
			<el-form-item>
				<el-button :disabled="loading" icon="Search" type="primary" @click="search">搜索 </el-button>
				<el-button :disabled="loading" type="primary" @click="addIdentify">添加企业证书</el-button>
			</el-form-item>
		</el-form>
		<el-table v-loading="loading" :data="tableData">
			<el-table-column :show-overflow-tooltip="true" label="企业名称" prop="name" width="400" />
			<el-table-column :show-overflow-tooltip="true" label="证书等级" prop="grade" width="80" />
			<el-table-column :show-overflow-tooltip="true" label="证书编号" prop="num" width="200" />
			<el-table-column :show-overflow-tooltip="true" label="企业地址" prop="addr" width="" />
			<el-table-column :show-overflow-tooltip="true" label="添加时间" prop="createTime" width="160" />
			<el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="160">
				<template #default="scope">
					<el-button icon="Edit" link type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
					<el-button icon="Delete" link type="danger" @click="handleDelete(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination
			v-show="total > 0"
			:total="total"
			v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize"
			@pagination="search"></pagination>

		<el-dialog :title="rowId ? '编辑证书' : '添加证书'" append-to-body destroy-on-close center v-model="editVisible" @open="onOpen" @close="onClose">
			<el-form ref="elForm" :model="formData" :rules="rules" label-width="100px" :size="'default'">
				<el-form-item label="企业名称" prop="name">
					<el-input v-model="formData.name" :style="{ width: '100%' }" clearable placeholder="请输入企业名称"></el-input>
				</el-form-item>
				<el-form-item label="企业地址" prop="addr">
					<el-input v-model="formData.addr" :style="{ width: '100%' }" clearable placeholder="请输入企业地址"> </el-input>
				</el-form-item>
				<el-form-item label="证书等级" prop="grade">
					<el-input v-model="formData.grade" clearable placeholder="请输入证书等级"></el-input>
				</el-form-item>
				<el-form-item label="证书编号" prop="num">
					<el-input v-model="formData.num" :style="{ width: '100%' }" clearable placeholder="请输入证书编号"> </el-input>
				</el-form-item>
				<el-form-item label="证书照片" prop="fileId" required>
					<el-upload
						ref="fileId"
						:accept="'.jpg,.jpeg,.png'"
						:action="fileAction"
						:before-upload="photoBeforeUpload"
						:headers="{
							Authorization: 'Bearer ' + getToken(),
						}"
						:limit="1"
						:list-type="'picture'"
						:on-remove="handleRemove"
						:on-success="uploadSuccess"
						:file-list="imageList"
						:show-file-list="false">
						<el-button :disabled="formData.fileUrl !== null && formData.fileUrl !== ''" icon="Upload" :size="'small'" type="primary"
							>点击上传
						</el-button>
						<el-button size="small" type="warning" @click.stop="clearFile">清空上传</el-button>
					</el-upload>
				</el-form-item>
				<el-form-item v-if="formData.fileUrl !== null && formData.fileUrl !== ''" prop="fileUrl">
					<el-image :preview-src-list="[formData.fileUrl]" :src="formData.fileUrl" style="width: 100px; height: 100px"> </el-image>
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input
						v-model="formData.remark"
						:autosize="{ minRows: 4, maxRows: 4 }"
						:style="{ width: '100%' }"
						placeholder="请输入备注"
						type="textarea"></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="closeDialog">取消</el-button>
					<el-button type="primary" @click="submitForm">确定</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<style lang="scss" scoped>
.pagination-container {
	background: #fff;
	padding: 32px 16px;
}
.pagination-container.hidden {
	display: none;
}
</style>
